package com.xjscrm.server.service.groupsendjob.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.mobile.collect.api.dto.msg.MicaFriendTalkMsg;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.common.util.SleepTimeTools;
import com.xjscrm.server.dto.groupsendtask.GroupSendTaskQuery;
import com.xjscrm.server.dto.wwcustomer.WwCustomerQuery;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.groupsendjob.GroupSendJobService;
import com.xjscrm.server.service.groupsendjob.GroupSendMsgService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 群发任务异步实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class GroupSendJobServiceImpl implements GroupSendJobService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GroupSendTaskMapper groupSendTaskMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private GroupSendMsgService groupSendMsgService;
    @Autowired
    private GroupSendJobDeviceMapper groupSendJobDeviceMapper;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private GroupSendTaskDeviceMapper groupSendTaskDeviceMapper;
    @Autowired
    private GroupSendTaskDeviceConfigMapper groupSendTaskDeviceConfigMapper;


    /**
     * 创建群发数据
     *
     * @param groupSendTask
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    public void addGroupSendJob(GroupSendTask groupSendTask){
        try {
            if (groupSendTask == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
            }

            int now = DateUtil.getTime();

            //新建群发消息
            GroupSendJob groupSendJob = new GroupSendJob();
            groupSendJob.setId(IdWorker.getId());
            groupSendJob.setMerId(groupSendTask.getMerId());
            groupSendJob.setTaskId(groupSendTask.getId());
            groupSendJob.setName(groupSendTask.getName());
            groupSendJob.setType(groupSendTask.getType());
            groupSendJob.setSendTime(groupSendTask.getSendTime());
            groupSendJob.setTime(groupSendTask.getTime());
            groupSendJob.setWeek(groupSendTask.getWeek());
            groupSendJob.setDay(groupSendTask.getDay());
            groupSendJob.setCustomerSwitch(groupSendTask.getCustomerSwitch());
            groupSendJob.setCustomerType(groupSendTask.getCustomerType());
            groupSendJob.setCustomerEnterpriseTagOpt(groupSendTask.getCustomerEnterpriseTagOpt());
            groupSendJob.setCustomerEnterpriseTags(groupSendTask.getCustomerEnterpriseTags());
            groupSendJob.setCustomerCreateDayStart(groupSendTask.getCustomerCreateDayStart());
            groupSendJob.setCustomerCreateDayEnd(groupSendTask.getCustomerCreateDayEnd());
            groupSendJob.setCustomerRemarkOpt(groupSendTask.getCustomerRemarkOpt());
            groupSendJob.setCustomerGenders(groupSendTask.getCustomerGenders());
            groupSendJob.setGroupSwitch(groupSendTask.getGroupSwitch());
            groupSendJob.setGroupType(groupSendTask.getGroupType());
            groupSendJob.setGroupNameKeywordOpt(groupSendTask.getGroupNameKeywordOpt());
            groupSendJob.setGroupNameKeywords(groupSendTask.getGroupNameKeywords());
            groupSendJob.setGroupTagOpt(groupSendTask.getGroupTagOpt());
            groupSendJob.setGroupTags(groupSendTask.getGroupTags());
            groupSendJob.setGroupMemberIdentitys(groupSendTask.getGroupMemberIdentitys());
            groupSendJob.setGroupMemberTotalMin(groupSendTask.getGroupMemberTotalMin());
            groupSendJob.setGroupMemberTotalMax(groupSendTask.getGroupMemberTotalMax());
            groupSendJob.setGroupCreateDayStart(groupSendTask.getGroupCreateDayStart());
            groupSendJob.setGroupCreateDayEnd(groupSendTask.getGroupCreateDayEnd());
            groupSendJob.setMsgType(groupSendTask.getMsgType());
            groupSendJob.setNotice(groupSendTask.getNotice());
            groupSendJob.setMsgDatas(groupSendTask.getMsgDatas());
            groupSendJob.setStatus(groupSendTask.getStatus());
            groupSendJob.setStartSendTime(groupSendTask.getHanderTime());
            groupSendJob.setCreateTime(now);
            groupSendJob.setUpdateTime(now);
            groupSendJob.setExcludeCustomerEnterpriseTagOpt(groupSendTask.getExcludeCustomerEnterpriseTagOpt());
            groupSendJob.setExcludeCustomerEnterpriseTags(groupSendTask.getExcludeCustomerEnterpriseTags());
            groupSendJob.setExcludeNewCustomer(groupSendTask.getExcludeNewCustomer());
            groupSendJob.setExcludeCustomerCreateDayStart(groupSendTask.getExcludeCustomerCreateDayStart());
            groupSendJob.setExcludeCustomerCreateDayEnd(groupSendTask.getExcludeCustomerCreateDayEnd());
            groupSendJob.setExcludeCustomerGenders(groupSendTask.getExcludeCustomerGenders());
            groupSendJob.setExcludeCustomerRemarkOpt(groupSendTask.getExcludeCustomerRemarkOpt());
            groupSendJob.setOpenExclude(groupSendTask.getOpenExclude());
            groupSendJobMapper.insertSelective(groupSendJob);

            //添加机器人表
            List<GroupSendTaskDevice> groupSendTaskDevices = groupSendTaskDeviceMapper.selectListByTaskId(groupSendTask.getId(), groupSendTask.getMerId());
            if(groupSendTaskDevices != null && groupSendTaskDevices.size() > 0){
                for (GroupSendTaskDevice groupSendTaskDevice : groupSendTaskDevices) {
                    //查询该机器人发送设置
                    GroupSendTaskDeviceConfig groupSendTaskDeviceConfig = groupSendTaskDeviceConfigMapper.selectByDeviceUniqueId(groupSendTaskDevice.getDeviceUniqueId(), groupSendTaskDevice.getMerId());
                    if(groupSendTaskDeviceConfig == null){
                        groupSendTaskDeviceConfig = new GroupSendTaskDeviceConfig();
                    }

                    //查询该机器人存不存在
                    WwDevice wwDevice = wwDeviceMapper.queryById(groupSendTaskDevice.getDeviceUniqueId());
                    if(wwDevice == null){ //不存在，则跳出
                        continue;
                    }

                    GroupSendJobDevice groupSendJobDevice = new GroupSendJobDevice();
                    groupSendJobDevice.setId(IdWorker.getId());
                    groupSendJobDevice.setMerId(groupSendTaskDevice.getMerId());
                    groupSendJobDevice.setJobId(groupSendJob.getId());
                    groupSendJobDevice.setDeviceUniqueId(groupSendTaskDevice.getDeviceUniqueId());
                    groupSendJobDevice.setDeviceId(wwDevice.getDeviceId());
                    groupSendJobDevice.setRateMin(Tools.getInteger(groupSendTaskDeviceConfig.getRateMin()));
                    groupSendJobDevice.setRateMax(Tools.getInteger(groupSendTaskDeviceConfig.getRateMax()));
                    groupSendJobDevice.setRule(groupSendTaskDeviceConfig.getRule());
                    groupSendJobDevice.setDelaySnapshot(0); //默认快照为0
                    groupSendJobDevice.setCreateTime(now);
                    groupSendJobDevice.setUpdateTime(now);
                    groupSendJobDeviceMapper.insertSelective(groupSendJobDevice);

                    //封装该机器人发送消息
                    groupSendMsgService.addGroupSendMsg(groupSendJob.getMerId(), groupSendJob, groupSendJobDevice);

                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

    }

    /**
     * 处理该任务的群发消息
     *
     * @param groupSendJob
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    public void groupSendJobSendMsg(GroupSendJob groupSendJob){
        if (groupSendJob == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群发任务不存在");
        }

        //查询该任务涉及机器人列表
        List<GroupSendJobDevice> groupSendJobDeviceList = groupSendJobDeviceMapper.selectByJobId(groupSendJob.getId(), groupSendJob.getMerId());
        if(groupSendJobDeviceList != null && groupSendJobDeviceList.size() > 0){
            for (GroupSendJobDevice groupSendJobDevice : groupSendJobDeviceList) {
                try {
                    //限制是否休眠
                    OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(groupSendJobDevice.getRule(), OperatorPlanDeviceRule.class);
                    boolean sleepFlag = SleepTimeTools.verifySleepTime(operatorPlanDeviceRule);
                    if(!sleepFlag){
                        groupSendMsgService.groupSendJobMsgToMqSync(groupSendJob.getMerId(), groupSendJob, groupSendJobDevice);
                    }
                }catch (Exception e){
                    log.error("处理群发任务的群发消息失败", e.getMessage(), e);
                }

            }
        }

    }


}
